package com.cn.wanix.servlet.product;

import com.alibaba.fastjson.JSON;
import com.cn.wanix.model.CuisineModel;
import com.cn.wanix.model.ProductModel;
import com.cn.wanix.model.ResultModel;
import com.cn.wanix.model.UserModel;
import com.cn.wanix.service.ProductService;
import com.cn.wanix.service.UserService;
import com.cn.wanix.service.impl.ProductServiceImpl;
import com.cn.wanix.service.impl.UserServiceImpl;
import com.cn.wanix.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * /back/user/findAll 查询所有
 * /back/user/add 保存  新增
 * /back/user/update 修改
 * /back/user/del 删除
 * /back/user/findById  根据id查询
 * /back/user/count  查询总条数
 * ---------------------------------
 * 后台代码：
 * servlet
 */
@WebServlet("/back/product/add")
public class ProductAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        0.乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        1.拿到页面的数据
        String name = req.getParameter("name");
        String cuisine = req.getParameter("cuisine");
        String price = req.getParameter("price");
        String imgHref = req.getParameter("imgHref");
//        2.封装model
        ProductModel productModel = new ProductModel();
        productModel.setName(name);
        productModel.setPrice(Tool.stringToFloat(price));
        productModel.setImgHref(imgHref);
        CuisineModel cuisineModel=new CuisineModel();
        cuisineModel.setId(Tool.stringToInt(cuisine));
        productModel.setCuisineModel(cuisineModel);
//        3.调用服务逻辑层
        ProductService productService = new ProductServiceImpl();
//        如果参数能够封装成一个对象，就必须封装

//        4.返回一个结果
        ResultModel resultModel = productService.add(productModel);
//        5.返回页面状态
//        PrintWriter out = resp.getWriter();
        String resJSON = JSON.toJSONString(resultModel);     // 转换为json
        resp.getWriter().print(resJSON); // 输出

    }
}
